package top.archiesean.authorize.controlle;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import top.archiesean.authorize.service.IRegisteredClient;

import java.security.Principal;
import java.util.*;

/**
 * @author ArchieSean
 * @description 令牌相关
 * @date 2024-01-08 11:23
 */
@Slf4j
@RestController
@RequestMapping("token")
@RequiredArgsConstructor
public class SeanTokenEndpoint {

    private final IRegisteredClient iRegisteredClient;


    /**
     * 登录页面接口
     *
     * @param modelAndView 视图
     * @param error        错误信息
     * @return ModelAndView
     */
    @GetMapping("login")
    public ModelAndView login(ModelAndView modelAndView, @RequestParam(required = false, name = "error") String error) {
        modelAndView.setViewName("login");
        modelAndView.addObject("error", error);
        return modelAndView;
    }

    /**
     * 授权码模式，确认页面
     *
     * @param modelAndView 视图
     * @param principal    用户信息
     * @param clientId     客户端id
     * @param scope        授权范围
     * @param state        状态
     * @return 视图
     */

    @GetMapping("confirm")
    public ModelAndView confirm(ModelAndView modelAndView, Principal principal,
                                @RequestParam(OAuth2ParameterNames.CLIENT_ID) String clientId,
                                @RequestParam(OAuth2ParameterNames.SCOPE) String scope,
                                @RequestParam(OAuth2ParameterNames.STATE) String state
    ) {
        Map<String, Object> map = iRegisteredClient.findOneByClientId(clientId, scope);
        modelAndView.addObject("clientId", clientId);
        modelAndView.addObject("state", state);
        modelAndView.addObject("scopeMap", map);
        modelAndView.addObject("principalName", principal.getName());
        modelAndView.setViewName("confirm");
        return modelAndView;
    }
}
